<template>
	<view>
		<button type="primary" @tap="chooseVideo">选择视频</button>
		<view class="preview" v-if="video">
			预览视频:
			<video :src="video" controls></video>
			<textarea v-model="title" placeholder="请输入视频的描述" />
			<view class="pickcat">
				选择视频分类:
				<picker mode="selector" :range="categories"
						 range-key="cat_name"
						 :value="selected"
						 @change="pickerSelected">
						<view class="catname">{{categories[selected].cat_name}}</view>
				</picker>
			</view>
			<button :disabled="title == ''" type="primary" @tap="uploadVideo">确定发布</button>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				selected:0,
				//预览视频路径
				video:'',
				//视频描述
				title:'',
				//分类列表
				categories:[],
			}
		},
		onLoad() {
			uniCloud.callFunction({
				name:'getCategories',
				data:{},
				success: (res) => {
					this.categories=res.result.data
				}
			})
		},
		 created(){
			//判断是否已经登录
			if(this.$store.state.id == ''){
				//跳转登录页面
				uni.redirectTo({
					url:'/pages/login/login'
				})
			}
		 },
		methods: {
			//选中分类
			pickerSelected(e){
				//修改当前选中的分类
				this.selected=e.target.value
			},
			//选择手机上的视频或者录制
			chooseVideo(){
				uni.chooseVideo({
					success:(res) =>{
						//把选择的视频路径设置到video上
						this.video=res.tempFilePath
					}
				})
			},
			//上传视频
			uploadVideo(){
				//弹出提示框
				uni.showLoading({
					title:'视频正在上传中...',
					//后面内容不能点击
					mask:true
				})
				//上传到云服务器
				uniCloud.uploadFile({
					filePath:this.video,
					success:(res) =>{
						//把视频信息保存到云数据库中
						uniCloud.callFunction({
							//函数名
							name:'addVideo',
							//提交数据
							data:{
								openid:this.$store.state.id,
								username:this.$store.state.username,
								avatar:this.$store.state.avatar,
								video:res.fileID,
								title:this.title,
								//获取当前选中的分类id
								cateid:this.categories[this.selected]._id
							},
							success: (res) => {
								//跳转首页
								uni.switchTab({
									url:'../index/index'
								})
								//提示上传成功
								uni.showToast({
									title:'上传成功',
									icon:'success'
								})
								//清空表单中的数据
								this.title=''
								this.video=''
							}
						})
					}
				})
			}
		}
	}
</script>

<style>
	video{
		width: 100%;
		margin-top: 50rpx;
	}
    textarea{
	    height: 200rpx;
     }
	 .pickcat{
		 padding: 30rpx 0;
	 }
	 .pickcat .catname{
		 padding: 20rpx 0;
		 text-align: center;
	 }
</style>
